package tcp

import (
	"gitee.com/lipore/go-nio/pkg/transport"
	"net"
	"reflect"
	"time"
)

type tcpTransport struct {
	id   int64
	conn *net.TCPConn
}

func (t *tcpTransport) ID() int64 {
	return t.id
}

func newTcpTransport(id int64, conn *net.TCPConn) transport.Transport {
	return &tcpTransport{
		id:   id,
		conn: conn,
	}
}

func (t *tcpTransport) FD() int {
	v := reflect.ValueOf(t.conn)
	netFD := reflect.Indirect(reflect.Indirect(v).FieldByName("fd"))
	pfd := reflect.Indirect(netFD.FieldByName("pfd"))
	fd := int(pfd.FieldByName("Sysfd").Int())
	return fd
}

func (t *tcpTransport) Close() error {
	err := t.conn.Close()
	t.conn = nil
	return err
}

func (t *tcpTransport) Ready() {
}

func (t *tcpTransport) Read(p []byte) (int, error) {
	err := t.conn.SetReadDeadline(time.Now().Add(100 * time.Microsecond))
	if err != nil {
		return 0, err
	}
	return t.conn.Read(p)
}

func (t *tcpTransport) Write(p []byte) (n int, err error) {
	return t.conn.Write(p)
}
